#!/usr/bin/env python
# *-* encoding: utf8
# 
# Copyright (c) 2006 Stian Soiland
# 
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# 
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
# 
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
#
# Author: Stian Soiland <stian@soiland.no>
# URL: http://soiland.no/i/src/
# License: LGPL
#
"""Test OpenDHT

Tests for opendht.py.
"""

import uuid
import unittest
import opendht


class TestStore(unittest.TestCase):
    def setUp(self):
        self.name = str(uuid.UUID())
        self.dht = opendht.OpenDHT(self.name, ttl=60)
        self.assertEquals(self.name, self.dht.identifier)
    
    def testPutGetSingle(self):
        self.dht.put("fish", "soup")
        self.assertEquals("soup", self.dht.get("fish"))
    
    def testGetUnknown(self):
        self.assertEquals(None, self.dht.get("unknown"))
   
    def testPutGetMultiple(self):
        multiple = set("first second third".split())
        for thing in multiple:
            self.dht.put("multiple", thing)
        results = set(self.dht.get("multiple", 4))   
        self.assertEquals(multiple, results)
        
    def testTwoConnections(self):
        other = opendht.OpenDHT(self.name, ttl=60)
        self.dht.put("fromFirst", "hello")
        self.assertEquals("hello", other.get("fromFirst"))
        other.put("fromOther", "hey")
        self.assertEquals("hey", self.dht.get("fromOther"))
    
    def testUniqueKey(self):
        # Should generate a new random UUID
        other = opendht.OpenDHT(ttl=60)
        self.assertNotEquals(self.dht.identifier, other.identifier)
        self.dht.put("unique", "hello")
        self.assertEquals(None, other.get("unique"))
        other.put("alsoUnique", "hey")
        self.assertEquals("hey", other.get("alsoUnique"))
        self.assertEquals(None, self.dht.get("alsoUnique"))
        
    def testPutGetMany(self):
        how_many = 128
        many = set()
        for x in range(how_many):
            many.add("value%s" % x)
        for thing in many:
            self.dht.put("many", thing)
        results = set(self.dht.get("many", how_many*2))   
        self.assertEquals(many, results)


if __name__ == "__main__":
    unittest.main()
    
